'use strict';

const Controller = require('egg').Controller;
const Res = require('../utils/response');
const joi = require("joi")

class UsersController extends Controller {
  async show() {
    const {
      ctx
    } = this;
    const schema = {
      user_id: joi.number().required(),
      favorite_type: joi.number().required(),
    }
    const {
      error,
      value
    } = joi.validate(ctx.request.query, schema);
    if (error) {
      ctx.status = 201;
      return ctx.body = Res(201, error, '操作失败');
    }
    const favoriteList = await ctx.model.Favorite.findAll({
      where: {
        user_id: value.user_id,
        favorite_type: value.favorite_type
      },
    });
    let result = [];
    if (value.favorite_type === 1) {
      for (let i = 0; i < favoriteList.length; i++) {
        let res = await await ctx.model.CookBook.findOne({
          where: {
            id: favoriteList[i].cook_id
          }
        })
        result.push(res);
      }
    } else {
      for (let i = 0; i < favoriteList.length; i++) {
        let res = await await ctx.model.Users.findOne({
          where: {
            id: favoriteList[i].favorite_user_id
          }
        })
        result.push(res);
      }
    }
    ctx.body = Res(0, result);
  }

  // 点赞
  async setFavoriteCount() {
    const ctx = this.ctx;
    const schema = {
      user_id: joi.number().required(),
      favorite_type: joi.number().required(),
      favorite_user_id: joi.number().required()
    }
    const {
      error,
      value
    } = joi.validate(ctx.request.body, schema);
    if (error) {
      ctx.status = 201;
      return ctx.body = Res(201, error.toString(), '操作失败');
    }

    const item = await ctx.model.Users.findByPk(value.favorite_user_id);
    if (!item) {
      ctx.status = 404;
      return;
    }
    await ctx.model.Favorite.findOrCreate({
      where: {
        favorite_user_id: value.favorite_user_id
      },
      defaults: {
        favorite_user_id: value.favorite_user_id,
        favorite_type: value.favorite_type,
        user_id: value.user_id
      }
    })
    ctx.body = Res(0, item);
  }

  // 取消收藏
  async cancel() {
    const ctx = this.ctx;
    const schema = {
      user_id: joi.number().required(),
      favorite_type: joi.number().required(),
      cook_id: joi.number(),
      favorite_user_id: joi.number()
    }
    const {
      error,
      value
    } = joi.validate(ctx.request.body, schema);
    if (error) {
      ctx.status = 201;
      return ctx.body = Res(201, error, '操作失败');
    }
    const where = value.favorite_type === 1 ? {
      cook_id: value.cook_id
    } : {
      favorite_user_id: value.favorite_user_id
    };
    const result = await ctx.model.Favorite.findOne({
      where: {
        user_id: value.user_id,
        favorite_type: value.favorite_type,
        ...where
      },
    });
    const res = await result.destroy();
    ctx.body = Res(0, res);
  }
}

module.exports = UsersController;